from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Count, Sum
from django.utils import timezone
from api.models import Food, FoodCategory, FoodSpec, FoodImage, Order, OrderItem, User
import json
from datetime import timedelta
from django.db.models import Q
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import JsonResponse
from django.urls import reverse
from django.template.loader import render_to_string
from django.views.decorators.http import require_POST
import logging
from django.contrib.auth import authenticate, login

# 导入图像处理工具
from utils.image_utils import ImageProcessor

logger = logging.getLogger('api')

# 登录视图
def custom_login(request):
    """自定义登录视图，解决Django admin和dashboard登录问题"""
    # 如果用户已登录，直接重定向到dashboard首页
    if request.user.is_authenticated:
        next_url = request.GET.get('next') or reverse('dashboard:home')
        if next_url and not next_url.startswith('/'):
            next_url = reverse('dashboard:home')
        return redirect(next_url)
        
    error_message = None
    
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        remember_me = request.POST.get('remember_me')
        
        if not username or not password:
            error_message = '请输入用户名和密码'
        else:
            # 使用Django的认证系统验证用户
            user = authenticate(request, username=username, password=password)
            
            if user is not None:
                # 检查用户是否有管理员权限或员工权限
                if user.is_superuser or user.is_staff or user.role in ['admin', 'staff']:
                    # 登录成功
                    login(request, user)
                    
                    # 如果不记住我，会话将在浏览器关闭时过期
                    if not remember_me:
                        request.session.set_expiry(0)
                    
                    # 获取next参数，如果有则重定向到该URL
                    next_url = request.POST.get('next') or request.GET.get('next') or reverse('dashboard:home')
                    # 进行额外的安全检查，确保next参数是有效的URL
                    if next_url and not next_url.startswith('/'):
                        next_url = reverse('dashboard:home')
                    
                    return redirect(next_url)
                else:
                    error_message = '您没有访问后台的权限'
            else:
                error_message = '用户名或密码错误'
    
    # 传递next参数，以便登录后重定向到正确的页面
    context = {
        'error_message': error_message,
        'next': request.GET.get('next', '')
    }
    return render(request, 'dashboard/login.html', context)

# Create your views here.

# 仪表盘首页
@login_required
def dashboard_home(request):
    # 获取基本统计数据
    food_count = Food.objects.count()
    category_count = FoodCategory.objects.count()
    order_count = Order.objects.count()
    user_count = User.objects.count()
    
    # 获取最近订单
    recent_orders = Order.objects.order_by('-created_at')[:5]
    
    # 获取热门商品 - 根据订单项计数
    popular_foods = Food.objects.annotate(
        order_count=Count('orderitem')
    ).order_by('-order_count', '-is_hot')[:5]
    
    # 获取待处理订单数
    pending_orders = Order.objects.filter(status=2).count()  # 待发货状态为2
    
    # 获取今日订单数
    today = timezone.now().date()
    today_orders = Order.objects.filter(created_at__date=today).count()
    
    # 获取本月销售额
    month_start = today.replace(day=1)
    month_sales = Order.objects.filter(
        created_at__date__gte=month_start,
        status__in=[3, 4]  # 已完成和处理中的订单对应的状态码
    ).aggregate(sum=Sum('total_price'))['sum'] or 0
    
    # 订单状态分布数据
    order_status_counts = Order.objects.values('status').annotate(count=Count('id'))
    order_status_data = [0, 0, 0, 0]  # 待处理、处理中、已完成、已取消
    
    for status_count in order_status_counts:
        status = status_count['status']
        count = status_count['count']
        if status == 2:  # pending
            order_status_data[0] = count
        elif status == 3:  # processing
            order_status_data[1] = count
        elif status == 4:  # completed
            order_status_data[2] = count
        elif status == 5:  # cancelled
            order_status_data[3] = count
    
    # 销售趋势图数据 - 最近7天
    sales_labels = []
    sales_data = []
    
    for i in range(6, -1, -1):
        date = today - timedelta(days=i)
        date_str = date.strftime('%m-%d')
        sales_labels.append(date_str)
        
        # 获取当天销售额
        daily_sales = Order.objects.filter(
            created_at__date=date,
            status__in=[3, 4]  # 已完成和处理中的订单对应的状态码
        ).aggregate(sum=Sum('total_price'))['sum'] or 0
        
        sales_data.append(daily_sales)
    
    context = {
        'food_count': food_count,
        'category_count': category_count,
        'order_count': order_count,
        'user_count': user_count,
        'recent_orders': recent_orders,
        'popular_foods': popular_foods,
        'pending_orders': pending_orders,
        'today_orders': today_orders,
        'month_sales': month_sales,
        'active_menu': 'dashboard',
        'order_status_data': json.dumps(order_status_data),
        'sales_labels': json.dumps(sales_labels),
        'sales_data': json.dumps(sales_data),
    }
    
    return render(request, 'dashboard/dashboard.html', context)

# 菜品列表
@login_required
def food_list(request):
    foods = Food.objects.all().order_by('-created_at')
    categories = FoodCategory.objects.all()
    
    # 筛选处理
    category_id = request.GET.get('category')
    is_active = request.GET.get('is_active')
    keyword = request.GET.get('keyword')
    
    if category_id:
        foods = foods.filter(category_id=category_id)
    
    if is_active:
        is_active = True if is_active == 'true' else False
        foods = foods.filter(is_active=is_active)
    
    if keyword:
        foods = foods.filter(name__contains=keyword)
    
    context = {
        'foods': foods,
        'categories': categories,
        'active_menu': 'foods',
    }
    return render(request, 'dashboard/food_list.html', context)

# 添加/编辑菜品
@login_required
def food_edit(request, food_id=None):
    if food_id:
        food = get_object_or_404(Food, id=food_id)
        is_edit = True
    else:
        food = None
        is_edit = False
    
    categories = FoodCategory.objects.filter(is_active=True)
    
    if request.method == 'POST':
        # 获取表单数据
        name = request.POST.get('name')
        category_id = request.POST.get('category')
        description = request.POST.get('description', '')
        price = request.POST.get('price', '')
        original_price = request.POST.get('original_price', '')
        is_active = 'is_active' in request.POST
        is_hot = 'is_hot' in request.POST
        is_new = 'is_new' in request.POST
        image_url = request.POST.get('image_url', '')
        
        # 转换价格为整数
        try:
            # 如果价格为空字符串或None，为编辑模式时使用原值，否则默认为0
            if price == '' or price is None:
                price = food.price if food else 0
            else:
                price = int(float(price))
                
            # 对原价进行相同处理
            if original_price == '' or original_price is None:
                original_price = food.original_price if food else 0
            else:
                original_price = int(float(original_price))
                
        except (ValueError, TypeError):
            messages.error(request, '价格必须为数字')
            return render(request, 'dashboard/food_edit.html', {'food': food, 'categories': categories, 'active_menu': 'foods'})
        
        if not name:
            messages.error(request, '请输入菜品名称')
        elif not category_id:
            messages.error(request, '请选择菜品分类')
        else:
            try:
                category = FoodCategory.objects.get(id=category_id)
                
                if food:
                    # 更新现有菜品
                    food.name = name
                    food.category = category
                    food.description = description
                    food.price = price
                    food.original_price = original_price
                    food.is_active = is_active
                    food.is_hot = is_hot
                    food.is_new = is_new
                    
                    # 只在提供了新URL时更新
                    if image_url:
                        food.image_url = image_url
                        # 如果提供了URL，则清除文件图片
                        if food.image:
                            food.image = None
                else:
                    # 创建新菜品
                    food = Food(
                        name=name,
                        category=category,
                        description=description,
                        price=price,
                        original_price=original_price,
                        is_active=is_active,
                        is_hot=is_hot,
                        is_new=is_new,
                    )
                    
                    if image_url:
                        food.image_url = image_url
                
                # 处理上传的图片
                if 'image_file' in request.FILES:
                    # 记录图像处理开始
                    logger.info(f"Dashboard处理食品图片上传: {name}")
                    food.image = request.FILES['image_file']
                    # 如果上传了文件，则清除URL
                    food.image_url = ''
                
                food.save()
                
                # 添加成功消息
                if is_edit:
                    messages.success(request, f'菜品 "{name}" 已更新')
                else:
                    messages.success(request, f'菜品 "{name}" 已添加')
                    
                # 重定向到菜品列表页面
                return redirect('dashboard:food_list')
                
            except FoodCategory.DoesNotExist:
                messages.error(request, '所选分类不存在')
            except Exception as e:
                messages.error(request, f'保存菜品时出错: {str(e)}')
    
    context = {
        'food': food,
        'categories': categories,
        'active_menu': 'foods',
    }
    return render(request, 'dashboard/food_edit.html', context)

# 订单列表
@login_required
def order_list(request):
    orders = Order.objects.all().order_by('-created_at')
    
    # 搜索和筛选
    search = request.GET.get('search', '')
    status = request.GET.get('status', '')
    date_from = request.GET.get('date_from', '')
    date_to = request.GET.get('date_to', '')
    
    # 应用筛选条件
    if search:
        orders = orders.filter(
            Q(order_number__icontains=search) | 
            Q(table_number__icontains=search) |
            Q(user__username__icontains=search)
        )
    
    if status:
        try:
            if ',' in status:
                # 分割并转换为整数列表
                status_values = [int(s.strip()) for s in status.split(',') if s.strip().isdigit()]
                if status_values:
                    orders = orders.filter(status__in=status_values)
            else:
                status_int = int(status)
                orders = orders.filter(status=status_int)
        except ValueError:
            pass
    
    if date_from:
        orders = orders.filter(created_at__date__gte=date_from)
    
    if date_to:
        orders = orders.filter(created_at__date__lte=date_to)
    
    # 分页处理
    paginator = Paginator(orders, 20)  # 每页显示20条
    page = request.GET.get('page')
    try:
        orders = paginator.page(page)
    except PageNotAnInteger:
        orders = paginator.page(1)
    except EmptyPage:
        orders = paginator.page(paginator.num_pages)
    
    # 统计数据，按照新的5个分类统计
    pending_orders = Order.objects.filter(status=1).count()  # 待确认
    processing_orders = Order.objects.filter(status=2).count()  # 制作中
    completed_orders = Order.objects.filter(status=3).count()  # 已完成
    cancelled_orders = Order.objects.filter(status=4).count()  # 已取消
    
    # 获取今日订单数
    today = timezone.now().date()
    today_orders_count = Order.objects.filter(created_at__date=today).count()
    
    # 今日销售额
    today_sales = Order.objects.filter(
        created_at__date=today,
        status__in=[2, 3]  # 制作中和已完成的订单
    ).aggregate(sum=Sum('total_price'))['sum'] or 0
    
    # 计算订单完成率
    total_orders = Order.objects.all().count()
    completed_rate = int((completed_orders / total_orders * 100)) if total_orders > 0 else 0
    
    context = {
        'orders': orders,
        'pending_orders': pending_orders,  # 待确认
        'processing_orders': processing_orders,  # 制作中
        'completed_orders': completed_orders,  # 已完成
        'cancelled_orders': cancelled_orders,  # 已取消
        'today_orders_count': today_orders_count,
        'today_sales': today_sales,
        'completed_rate': completed_rate,
        'search': search,
        'status': status,
        'date_from': date_from,
        'date_to': date_to,
        'active_menu': 'orders',
    }
    return render(request, 'dashboard/order_list.html', context)

# 订单详情
@login_required
def order_detail(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    order_items = order.items.all()
    
    if request.method == 'POST':
        action = request.POST.get('action', '')
        
        if action == 'update_status':
            new_status = int(request.POST.get('status', 1))
            order.status = new_status
            
            # 更新相应的时间标记
            if new_status == 2 and order.paid_at is None:  # 更新为制作中
                order.paid_at = timezone.now()
            elif new_status == 3 and order.finished_at is None:  # 更新为已完成
                order.finished_at = timezone.now()
            elif new_status == 4 and order.canceled_at is None:  # 更新为已取消
                order.canceled_at = timezone.now()
                
            order.save()
            messages.success(request, f'订单状态已更新为: {dict(Order.ORDER_STATUS)[new_status]}')
        
        elif action == 'update_remark':
            remark = request.POST.get('remark', '')
            order.remark = remark
            order.save()
            messages.success(request, f'订单备注已更新')
        
        return redirect('dashboard:order_detail', order_id=order_id)
    
    # 获取可追踪的状态时间节点
    status_timeline = []
    status_timeline.append({
        'status': '创建订单',
        'time': order.created_at,
        'icon': 'fa-shopping-cart',
        'color': 'primary'
    })
    
    if order.paid_at:
        status_timeline.append({
            'status': '已付款',
            'time': order.paid_at,
            'icon': 'fa-credit-card',
            'color': 'info'
        })
    
    if order.finished_at:
        status_timeline.append({
            'status': '订单完成',
            'time': order.finished_at,
            'icon': 'fa-check-circle',
            'color': 'success'
        })
    
    if order.canceled_at:
        status_timeline.append({
            'status': '订单取消',
            'time': order.canceled_at,
            'icon': 'fa-times-circle',
            'color': 'danger'
        })
    
    context = {
        'order': order,
        'order_items': order_items,
        'status_timeline': status_timeline,
        'active_menu': 'orders',
    }
    return render(request, 'dashboard/order_detail.html', context)

# 订单状态更新
@login_required
def order_update_status(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    
    if request.method == 'POST':
        try:
            new_status = int(request.POST.get('status', 1))
            note = request.POST.get('note', '')
            
            # 更新状态
            order.status = new_status
            
            # 根据状态更新相应的时间字段
            if new_status == 2 and order.paid_at is None:  # 更新为制作中
                order.paid_at = timezone.now()
            elif new_status == 3 and order.finished_at is None:  # 更新为已完成
                order.finished_at = timezone.now()
            elif new_status == 4 and order.canceled_at is None:  # 更新为已取消
                order.canceled_at = timezone.now()
                
                # 如果提供了备注，则更新订单备注
                if note:
                    if order.remark:
                        order.remark += f"\n[取消原因] {note}"
                    else:
                        order.remark = f"[取消原因] {note}"
            
            order.save()
            messages.success(request, f'订单 #{order.order_number} 状态已更新')
        except Exception as e:
            messages.error(request, f'更新订单状态时出错：{str(e)}')
    
    # 获取重定向URL
    next_url = request.POST.get('next', 'dashboard:order_list')
    
    if next_url.startswith('/'):
        return redirect(next_url)
    return redirect(next_url)

# 直接更新订单状态
@login_required
def order_update_status_direct(request, order_id, status):
    order = get_object_or_404(Order, id=order_id)
    
    try:
        # 更新状态
        order.status = status
        
        # 根据状态更新相应的时间字段
        if status == 2 and order.paid_at is None:  # 更新为制作中
            order.paid_at = timezone.now()
        elif status == 3 and order.finished_at is None:  # 更新为已完成
            order.finished_at = timezone.now()
        elif status == 4 and order.canceled_at is None:  # 更新为已取消
            order.canceled_at = timezone.now()
        
        order.save()
        messages.success(request, f'订单 #{order.order_number} 状态已更新')
    except Exception as e:
        messages.error(request, f'更新订单状态时出错：{str(e)}')
    
    # 获取重定向URL
    next_url = request.GET.get('next', 'dashboard:order_list')
    
    if next_url.startswith('/'):
        return redirect(next_url)
    return redirect(next_url)

# 订单打印
@login_required
def order_print(request, order_id):
    order = get_object_or_404(Order, id=order_id)
    order_items = order.items.all()
    
    context = {
        'order': order,
        'order_items': order_items,
    }
    return render(request, 'dashboard/order_print.html', context)

# 导出订单数据
@login_required
def order_export(request):
    import csv
    from django.http import HttpResponse
    
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="orders.csv"'
    
    # 获取筛选条件
    search = request.GET.get('search', '')
    status = request.GET.get('status', '')
    date_from = request.GET.get('date_from', '')
    date_to = request.GET.get('date_to', '')
    
    # 构建查询
    orders = Order.objects.all().order_by('-created_at')
    
    # 应用筛选条件
    if search:
        orders = orders.filter(
            Q(order_number__icontains=search) | 
            Q(table_number__icontains=search) |
            Q(user__username__icontains=search)
        )
    
    if status:
        try:
            status_int = int(status)
            orders = orders.filter(status=status_int)
        except ValueError:
            pass
    
    if date_from:
        orders = orders.filter(created_at__date__gte=date_from)
    
    if date_to:
        orders = orders.filter(created_at__date__lte=date_to)
    
    # 写入CSV头
    writer = csv.writer(response)
    writer.writerow(['订单号', '下单时间', '用户', '桌号/取餐号', '收货人', '联系电话', '总金额', '状态', '备注'])
    
    # 写入数据
    for order in orders:
        status_text = order.get_status_display()
        writer.writerow([
            order.order_number,
            order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            order.user.username,
            order.table_number or '',
            order.receiver or '',
            order.receiver_phone or '',
            float(order.total_price),
            status_text,
            order.remark or ''
        ])
    
    return response

# 批量操作订单
@login_required
def order_batch_action(request):
    if request.method == 'POST':
        action = request.POST.get('action')
        order_ids = request.POST.getlist('order_ids')
        
        if not order_ids:
            messages.warning(request, '请选择要操作的订单')
            return redirect('dashboard:order_list')
        
        orders = Order.objects.filter(id__in=order_ids)
        
        if action == 'mark_paid':
            # 将选中的待确认订单标记为制作中
            updated = 0
            for order in orders.filter(status=1):
                order.status = 2
                order.paid_at = timezone.now()
                order.save()
                updated += 1
            messages.success(request, f'已将{updated}个订单确认并开始制作')
        
        elif action == 'mark_delivered':
            # 将选中的制作中订单标记为已完成
            updated = 0
            for order in orders.filter(status=2):
                order.status = 3
                order.finished_at = timezone.now()
                order.save()
                updated += 1
            messages.success(request, f'已将{updated}个订单标记为已完成')
        
        elif action == 'mark_received':
            # 将选中的已完成订单标记为已完成
            updated = 0
            for order in orders.filter(status=3):
                order.status = 3
                order.save()
                updated += 1
            messages.success(request, f'已将{updated}个订单标记为已完成')
        
        elif action == 'mark_completed':
            # 将选中的已完成订单标记为已完成
            updated = 0
            for order in orders.filter(status=3):
                order.status = 3
                order.save()
                updated += 1
            messages.success(request, f'已将{updated}个订单标记为已完成')
        
        elif action == 'mark_cancelled':
            # 将选中的待确认订单标记为已取消
            updated = 0
            for order in orders.filter(status=1):
                order.status = 4
                order.canceled_at = timezone.now()
                order.save()
                updated += 1
            messages.success(request, f'已取消{updated}个订单')
    
    return redirect('dashboard:order_list')

# 分类列表
@login_required
def category_list(request):
    categories = FoodCategory.objects.all().order_by('sort_order')
    
    context = {
        'categories': categories,
        'active_menu': 'categories',
    }
    return render(request, 'dashboard/category_list.html', context)

# 添加/编辑分类
@login_required
def category_edit(request, category_id=None):
    # 获取分类或创建新分类
    category = None
    if category_id:
        category = get_object_or_404(FoodCategory, id=category_id)
    
    if request.method == 'POST':
        # 处理表单提交
        name = request.POST.get('name')
        sort_order = request.POST.get('sort_order') or 0
        is_active = 'is_active' in request.POST
        icon_url = request.POST.get('icon_url')
        
        # 获取上传的文件
        icon_file = request.FILES.get('icon_file')
        
        # 验证必填字段
        if not name:
            messages.error(request, '请填写分类名称')
        # 如果没有提供图标文件也没有提供图标URL，则显示错误消息
        elif not (icon_file or icon_url):
            messages.error(request, '请上传图标或提供图标URL')
        else:
            # 创建或更新分类
            if category:
                # 更新现有分类
                category.name = name
                category.sort_order = sort_order
                category.is_active = is_active
                
                # 如果上传了新图标，则更新icon字段
                if icon_file:
                    # 记录图像处理开始
                    logger.info(f"Dashboard处理分类图标上传: {name}")
                    category.icon = icon_file
                    category.icon_url = None  # 清空icon_url
                # 否则如果提供了图标URL，则更新icon_url字段
                elif icon_url:
                    category.icon_url = icon_url
                    # 如果之前有上传的图标，将其清空
                    if category.icon:
                        category.icon = None
                
                category.save()
                messages.success(request, f'分类 "{name}" 已更新')
            else:
                # 创建新分类
                category = FoodCategory(
                    name=name,
                    sort_order=sort_order,
                    is_active=is_active
                )
                
                # 如果上传了图标文件，则设置icon字段
                if icon_file:
                    category.icon = icon_file
                # 否则如果提供了图标URL，则设置icon_url字段
                elif icon_url:
                    category.icon_url = icon_url
                
                category.save()
                messages.success(request, f'分类 "{name}" 已创建')
            
            return redirect('dashboard:category_list')
    
    context = {
        'category': category,
        'active_menu': 'categories',
    }
    return render(request, 'dashboard/category_edit.html', context)

# 用户列表
@login_required
def user_list(request):
    users = User.objects.all().order_by('-date_joined')
    
    context = {
        'users': users,
        'active_menu': 'users',
    }
    return render(request, 'dashboard/user_list.html', context)

@login_required
def food_delete(request, food_id):
    food = get_object_or_404(Food, id=food_id)
    food_name = food.name
    
    # 执行删除操作
    food.delete()
    
    # 添加成功消息
    messages.success(request, f'菜品 "{food_name}" 已成功删除')
    
    # 重定向回菜品列表页面
    return redirect('dashboard:food_list')

@login_required
def category_delete(request, category_id):
    category = get_object_or_404(FoodCategory, id=category_id)
    category_name = category.name
    
    # 检查该分类下是否有菜品
    food_count = Food.objects.filter(category_id=category_id).count()
    if food_count > 0:
        messages.error(request, f'无法删除分类 "{category_name}"，该分类下还有 {food_count} 个菜品')
    else:
        # 执行删除操作
        category.delete()
        messages.success(request, f'分类 "{category_name}" 已成功删除')
    
    # 重定向回分类列表页面
    return redirect('dashboard:category_list')

@login_required
def user_edit(request, user_id=None):
    # 获取用户或准备创建新用户
    user = None
    is_add = user_id is None  # 判断是添加用户还是编辑用户
    
    if user_id:
        user = get_object_or_404(User, id=user_id)
    
    if request.method == 'POST':
        # 处理表单提交
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        phone = request.POST.get('phone')
        role = request.POST.get('role')
        is_active = 'is_active' in request.POST
        
        # 验证必填字段
        if not username:
            messages.error(request, '请填写用户名')
        # 如果是创建新用户且没有填写密码，显示错误
        elif not user and not password:
            messages.error(request, '请设置密码')
        else:
            try:
                if user:
                    # 更新现有用户
                    # 检查用户名是否已被其他用户使用
                    if User.objects.exclude(id=user.id).filter(username=username).exists():
                        messages.error(request, f'用户名 "{username}" 已被占用')
                        return redirect('dashboard:user_edit', user_id=user_id)
                    
                    user.username = username
                    user.email = email
                    user.first_name = first_name
                    user.last_name = last_name
                    user.phone = phone
                    user.role = role
                    user.is_active = is_active
                    
                    # 只有在提供了新密码时才更新密码
                    if password:
                        user.set_password(password)
                    
                    user.save()
                    messages.success(request, f'用户 "{username}" 已更新')
                else:
                    # 创建新用户
                    # 检查用户名是否已存在
                    if User.objects.filter(username=username).exists():
                        messages.error(request, f'用户名 "{username}" 已被占用')
                        return redirect('dashboard:user_add')
                    
                    # 创建新用户
                    user = User.objects.create_user(
                        username=username,
                        email=email,
                        password=password,
                        first_name=first_name,
                        last_name=last_name,
                        phone=phone,
                        role=role,
                        is_active=is_active
                    )
                    messages.success(request, f'用户 "{username}" 已创建')
                
                return redirect('dashboard:user_list')
            except Exception as e:
                messages.error(request, f'保存用户时出错: {str(e)}')
    
    context = {
        'user_obj': user,  # 使用user_obj避免与request.user冲突
        'is_add': is_add,  # 添加is_add标志
        'active_menu': 'users',
    }
    return render(request, 'dashboard/user_edit.html', context)

@login_required
def user_status_update(request, user_id):
    user = get_object_or_404(User, id=user_id)
    
    # 不允许修改自己的状态
    if request.user.id == user_id:
        messages.error(request, '不能修改自己的状态')
    else:
        # 切换用户状态
        user.is_active = not user.is_active
        user.save()
        status_text = '启用' if user.is_active else '禁用'
        messages.success(request, f'用户 "{user.username}" 已{status_text}')
    
    return redirect('dashboard:user_list')

@login_required
def user_delete(request, user_id):
    user = get_object_or_404(User, id=user_id)
    
    # 不允许删除自己
    if request.user.id == user_id:
        messages.error(request, '不能删除自己的账户')
    else:
        username = user.username
        user.delete()
        messages.success(request, f'用户 "{username}" 已删除')
    
    return redirect('dashboard:user_list')

@login_required
def user_batch_action(request):
    if request.method == 'POST':
        action = request.POST.get('action')
        user_ids = request.POST.getlist('user_ids')
        
        if not user_ids:
            messages.error(request, '请选择至少一个用户')
            return redirect('dashboard:user_list')
        
        # 确保不包含当前用户
        if str(request.user.id) in user_ids:
            messages.error(request, '不能对自己执行此操作')
            user_ids.remove(str(request.user.id))
            
            # 如果移除自己后没有其他用户，则返回
            if not user_ids:
                return redirect('dashboard:user_list')
        
        users = User.objects.filter(id__in=user_ids)
        
        if action == 'activate':
            # 批量启用
            users.update(is_active=True)
            messages.success(request, f'已启用 {len(user_ids)} 个用户')
        elif action == 'deactivate':
            # 批量禁用
            users.update(is_active=False)
            messages.success(request, f'已禁用 {len(user_ids)} 个用户')
        elif action == 'delete':
            # 批量删除
            deleted_count = 0
            for user in users:
                user.delete()
                deleted_count += 1
            messages.success(request, f'已删除 {deleted_count} 个用户')
    
    return redirect('dashboard:user_list')
